#!/usr/bin/perl
#
# Change the email domain of all users in a specific domain
#
# Invoke: changedomain olddomain newdomain
#

use Counter;
use Fcntl;

$olddom = shift;
$newdom = shift;

die "Usage: $0 olddom newdom\n" if !$olddom || !$newdom;

$users = Counter::open(O_RDWR);
$olddomsql = $olddom;
$olddomsql =~ s/\*/%/;
$olddomregexp = $olddom;
$olddomregexp =~ s/\*/.*/;
@tochange = $users->select("email like '%\@$olddomsql'");
print @tochange + 0, " users selected\n";
for $user (@tochange) {
    my $oldmail = $user->{email};
    my $key = $user->key();
    if ($user->{email} =~ s/\@$olddomregexp$/\@$newdom/) {
	print "Changing $key from $oldmail to $$user{email}\n";
	eval { $user->store()};
	if ($@) {
	    print "Storing failed: $@ - new already entered?\n";
	}
    } else {
	print "Substitution failed on $oldmail\n";
    }
}
